package org.javacore.io.encode;

import java.io.UnsupportedEncodingException;

/*
 * Copyright [2015] [Jeff Lee]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @author Jeff Lee
 * @since 2015-6-19 21:31:37
 * 	String编码规则
 */
public class StringEncodeT {
	
	@SuppressWarnings("unused")
	public static void main(String[] args) throws UnsupportedEncodingException {
		
		String name = "李强强Jeff";
		byte[] bytesA = name.getBytes();// 等价于getBytes("UTF-8")。 项目默认的编码 UTF-8
		for (byte b : bytesA)
			System.out.print(Integer.toHexString(b & 0xff) + " ");// 将字节以16进制方式显示
		/**
		 * 小结：UTF-8编码：中文占3个字节，英文占1个字节
		 */
	
		System.out.println();
		byte[] bytesB = name.getBytes("GBK");
		for (byte b : bytesB)
			System.out.print(Integer.toHexString(b & 0xff) + " ");
		/**
		 * 小结：GBK编码：中文占2个字节，英文占1个字节
		 */
		
		System.out.println();
		byte[] bytesC = name.getBytes("UTF-16BE");// Java是双字节编码，UTF-16BE
		for (byte b : bytesC)
			System.out.print(Integer.toHexString(b & 0xff) + " ");
		/**
		 * 小结：UTF-16BE编码：中文占2个字节，英文占2个字节
		 */
		
		// 以某种编码，字符串转字节序列。则字节序列转回字符串时需要用那种编码。否则会出现乱码。
		System.out.println();
		String name1 = new String(bytesA);
		String name2 = new String(bytesB,"UTF-8");
		String name3 = new String(bytesC,"UTF-16BE");
		System.out.println(name3);
		
		/**
		 * 补充：文本文件就是字节序列，任意的编码。
		 * 在中文机器上，创建文本文件，只认识ANSI编码。
		 */
	}
}
